from flask import Flask, json, render_template,request
from datetime import timedelta
from main.main import Main
from data_resource.global_resource import GlobalResource
# 下面代码解决了静态文件更新后不影响线上的原因
# 是因为flask 加载静态文件后，静态文件有保存期，设置保存期为1s则可以快速更新
api = Flask(__name__)
api.send_file_max_age_default = timedelta(seconds=1)
Main.init()
global_resource = GlobalResource.instance()


@api.route('/', methods=['POST', 'GET'])
def index():
    if request.method == "GET":
        return render_template('search_box_v2.html')
    elif request.method == "POST":
        query = request.form["query"]
        # channel 后期可以根据不同场景或者不同的垂类设置,使用不同的策略来处理query
        channel = "base"
        result = Main.do_query(query=query, channel=channel)

        # 测试数据
        test_str = ""
        for i in range(120):
            test_str += str(i)
        result = []
        for i in range(10):
            test_data = {"name": str(i), "description": test_str, "status": 1, "api_id": str(i)}
            result.append(test_data)
        # 测试数据

        if not result:
            result = []
        return render_template('search_box_v2.html', result=result)


@api.route('/api_page/<api_id>', methods=['POST', 'GET'])
def api_page(api_id):
    """
    通过api_id 查找到指定用户,传递给api_page中
    :param api_id:
    :return:
    """
    # 调用global_resource获取mysql连接
    # mysql_service = global_resource.resource_manager.get_service("mysql")
    # mysql_service.do sth
    data = {"name": "aaa","api_id": "semantichacker"}
    return render_template("api_page.html", data=data)


if __name__ == '__main__':
    api.run()

